package com.hxhy.util;


import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author gbzdyf@126.com
 * @Create: 2019/11/29 15:15
 */
public class AesUtilTest {

    /**
     * AES加密 ECB加密
     * @param encryptStr 待加密的base 64 code
     * @param decryptKey 加密密钥
     * @return 加密后的string
     * @throws Exception
     */
    public static String aesEncryptC(String encryptStr, String decryptKey) throws Exception {
        return parseByte2HexStr(aesEncryptToBytesC(encryptStr, decryptKey));
    }

    /**
     * AES加密 ECB
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    private static byte[] aesEncryptToBytesC(String content, String encryptKey) {
        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "AES");
            aesECB.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = aesECB.doFinal(content.getBytes("UTF-8"));
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**将二进制转换成16进制
     * @param buf
     * @return
     */
    private static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        if(buf==null){
            return sb.toString();
        }
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }
}
